/*
 * @Descripttion:
 * @version:
 * @Author: wujq
 * @Date: 2023-07-18 17:47:18
 * @LastEditors: Andy
 * @LastEditTime: 2023-08-09 16:08:53
 */

import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Switch, message, Button } from 'antd';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { postCustomAdd, postCustomModify } from '@api/knowledge';
import { bindActionCreators } from 'redux';
import CallbackModel from '@components/callback-model';
import { Link } from 'react-router-dom';
import { ENG_NAME } from '@util/constants';
import { withRouter } from 'react-router-dom';
import { actions as assetManageActions } from '@containers/asset-manage/reducer';
import _ from 'lodash';
const prefixCls = 'custom-fingerprint-form';
const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 19
  }
};
const FingerPrintForm = ({
  location,
  visible,
  setVisible,
  form,
  loadAssetCategoryList,
  getList,
  detail,
  setDetail
}) => {
  const { getFieldDecorator, validateFields, resetFields, setFieldsValue } = form;
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [edit, setEdit] = useState(false);
  const [callBackVisble, setCallBackVisble] = useState(false);
  const closeHandler = () => {
    setVisible(false);
    resetFields();
    setEdit(false);
    setDetail();
  };
  // eslint-disable-next-line no-unused-vars
  const validatorToUsername = (rule, value, callback) => {
    const re = new RegExp(ENG_NAME);
    const errorDist = {
      [!re.test(value)]: () => {
        return '用户名不能为中文和空格';
      },
      [value && value.length > 128]: () => {
        return '用户名长度最大为128';
      },
      [value && value.length < 2]: () => {
        return '用户名长度最小为2';
      },
      [!value]: () => {
        return '用户名不能为空';
      }
    };
    callback(errorDist[true]);
  };
  const handleSubmit = () => {
    // eslint-disable-next-line no-unused-vars
    validateFields((err, values) => {
      if (err) {
        return;
      }
      let newEnable;
      // eslint-disable-next-line no-undefined
      values.enable === undefined ? (newEnable = false) : (newEnable = values.enable);
      setConfirmLoading(true);
      let api = edit ? postCustomModify : postCustomAdd;
      edit ? (values.id = detail._id) : '';
      api({ ...values, enable: newEnable })
        .then(() => {
          message.success('新增成功');
          getList();
          closeHandler();
          !edit ? setCallBackVisble(true) : null;
        })
        .catch(e => {
          message.error(e.message);
        })
        .finally(() => {
          setConfirmLoading(false);
        });
    });
  };

  const callbackModelFoot = () => {
    return (
      <>
        <Button type="primary" style={{ margin: '0 10px' }}>
          <Link to="/knowledge-base/asset-identification?add=true">添加对应指纹知识库</Link>
        </Button>
        <Button
          type="primary"
          onClick={() => {
            setCallBackVisble(false);
            resetFields();
            setEdit(false);
            setDetail();
            setVisible(true);
          }}
        >
          继续添加指纹规则
        </Button>
      </>
    );
  };

  useEffect(() => {
    loadAssetCategoryList();
  }, []);

  useEffect(() => {
    if (!detail && visible) {
      setFieldsValue({ enable: true });
    }
  }, [visible]);

  useEffect(() => {
    const { search } = location;
    if (search) {
      const params = new URLSearchParams(search);
      if (params.get('add')) {
        setVisible(true);
      }
    }
  }, [location]);

  useEffect(() => {
    if (detail && detail._id) {
      setFieldsValue(detail);
      setEdit(true);
    }
  }, [detail]);
  return (
    <>
      <Modal
        title={`${edit ? '修改' : '添加'}指纹规则`}
        maskClosable={false}
        closable={true}
        width={500}
        onCancel={closeHandler}
        onOk={handleSubmit}
        visible={visible}
        className={prefixCls}
        confirmLoading={confirmLoading}
      >
        <Form {...formItemLayout}>
          <Form.Item label="规则名称">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '请输入规则名称'
                  // validator: validatorToUsername
                },

                {
                  max: 32,
                  message: '您输入的内容超过32个字符限制'
                }
              ]
            })(<Input placeholder="请输入规则名称" />)}
          </Form.Item>
          <Form.Item label="服务">
            {getFieldDecorator('service', {
              rules: [
                {
                  required: true,
                  message: '请输入服务'
                }
              ]
            })(<Input placeholder="如：http" />)}
          </Form.Item>
          <Form.Item label="规则">
            {getFieldDecorator('rule', {
              rules: [
                {
                  required: true,
                  message: '请输入规则名称'
                }
              ]
            })(<Input placeholder="如：^HTTP/1.1 200 OK" />)}
          </Form.Item>
          <Form.Item label="组件">
            {getFieldDecorator('product', {
              rules: [
                {
                  required: true,
                  message: '请输入组件'
                }
              ]
            })(<Input placeholder="如：$1" />)}
          </Form.Item>
          <Form.Item label="组件版本">
            {getFieldDecorator('productVersion')(<Input placeholder="如：$2" />)}
          </Form.Item>
          <Form.Item label="主机名">
            {getFieldDecorator('hostname')(<Input placeholder="如：$3" />)}
          </Form.Item>
          <Form.Item label="操作系统">
            {getFieldDecorator('os')(<Input placeholder="如：$4" />)}
          </Form.Item>
          <Form.Item label="设备类型">
            {getFieldDecorator('device')(<Input placeholder="如：$5 " />)}
          </Form.Item>
          <Form.Item label="厂商">
            {getFieldDecorator('company')(<Input placeholder="如：$6" />)}
          </Form.Item>
          <Form.Item label="品牌">
            {getFieldDecorator('brand')(<Input placeholder="如：$7" />)}
          </Form.Item>
          <Form.Item label="额外信息">
            {getFieldDecorator('extraInfo')(<Input placeholder="如：$8 " />)}
          </Form.Item>
          <div style={{ margin: '0 0 15px 24px' }}>
            <span style={{ color: 'rgba(0, 0, 0, 0.85)' }}>使用说明 : </span>
            <a href={'/自定义指纹规则说明文档.pdf'} type="link" target={'_blank'}>
              查看自定义指纹规则说明文档
            </a>
          </div>
          <Form.Item {...formItemLayout} colon={false} label="是否启用">
            {getFieldDecorator('enable', { valuePropName: 'checked' })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
      <CallbackModel
        visible={callBackVisble}
        setVisible={setCallBackVisble}
        footer={callbackModelFoot()}
        title="添加指纹规则成功"
        content="是否继续添加指纹规则"
      />
    </>
  );
};

const mapStateToProps = state => {
  return {
    assetCategoryTree: _.get(state, 'assetManage.assetCategoryTree', [])
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(assetManageActions, dispatch)
  };
};

FingerPrintForm.propTypes = {
  visible: PropTypes.bool,
  setVisible: PropTypes.func,
  form: PropTypes.object,
  assetCategoryTree: PropTypes.object,
  loadAssetCategoryList: PropTypes.func,
  getList: PropTypes.func,
  detail: PropTypes.object,
  setDetail: PropTypes.func,
  location: PropTypes
};
export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps
  )(Form.create()(FingerPrintForm))
);
